<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>商品秒杀页面</title>
    <link
            rel="stylesheet"
            href="https://g.alicdn.com/code/lib/bootstrap/4.5.3/css/bootstrap.min.css"
    />
    <style>
        body {
            background-color: #f8f9fa;
            color: #333;
            font-family: "Helvetica Neue", Arial, sans-serif;
        }

        .container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }

        .product-image {
            width: 100%;
            height: auto;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .product-info {
            padding: 20px;
        }

        .product-title {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #343a40;
        }

        .price {
            font-size: 32px;
            color: #e74c3c;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .original-price {
            text-decoration: line-through;
            color: #868e96;
            font-size: 18px;
            margin-left: 10px;
        }

        .sale-time {
            font-size: 20px;
            margin-bottom: 20px;
            color: #495057;
            font-weight: bold;
        }

        .btn-countdown {
            background-color: #e74c3c;
            border: none;
            font-size: 24px;
            font-weight: bold;
            padding: 15px 30px;
            transition: all 0.3s ease;
            width: 100%;
            color: #fff;
        }

        .btn-countdown:hover,
        .btn-countdown:focus {
            background-color: #c0392b;
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
        }

        .btn-countdown:disabled {
            background-color: #f8d7da;
            color: #721c24;
        }

        .btn-countdown .countdown-label {
            font-size: 16px;
            display: block;
            margin-bottom: 5px;
        }

        .product-description {
            margin-top: 30px;
            color: #495057;
        }

        .product-description h3 {
            color: #343a40;
            font-weight: bold;
            margin-bottom: 20px;
            background-color: #e9ecef;
            padding: 10px;
        }

        .feature-list li {
            margin-bottom: 10px;
            position: relative;
            padding-left: 25px;
        }

        .feature-list li:before {
            content: "✓";
            color: #20c997;
            position: absolute;
            left: 0;
            top: 0;
            font-weight: bold;
        }

        .status-message {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
        }

        .status-offline {
            background-color: #f8d7da;
            color: #721c24;
        }

        .spinner-border {
            display: none;
            vertical-align: text-bottom;
            margin-right: 5px;
        }

        .loading {
            position: relative;
        }

        .loading::after {
            content: "";
            position: absolute;
            top: 50%;
            left: 30%;
            width: 2rem;
            height: 2rem;
            border-radius: 50%;
            border: 4px solid #fff;
            border-top-color: red;
            animation: spin 0.75s linear infinite;
            transform: translate(-50%, -50%);
        }

        @keyframes spin {
            from {
                transform: translate(-50%, -50%) rotate(0deg);
            }
            to {
                transform: translate(-50%, -50%) rotate(360deg);
            }
        }

        /* 自定义遮罩透明度 */
        .modal-backdrop.show {
            background-color: rgba(128, 128, 128, 0.8) !important; /* 强制应用灰色遮罩 */
        }

        /* 标题背景颜色 */
        .modal-header {
            background-color: #e74c3c; /* 蓝色背景 */
            color: white; /* 白色字体 */
        }

        /* 增加内容区域的高度 */
        .modal-body {
            min-height: 100px; /* 设置最小高度 */
        }

        .stock-info {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
        }

        .stock-info .card-body {
            padding: 0.75rem 1rem;
        }

        .stock-item {
            display: flex;
            align-items: center;
            font-size: 0.95rem;
        }

        .stock-item i {
            font-size: 1.2rem;
        }

        .stock-item strong {
            font-size: 1.1rem;
            margin-left: 0.25rem;
        }

        .stock-info #remainingStock {
            font-size: 1.2rem;
        }
    </style>
</head>

<body>
<div class="container mt-4">
    <div class="d-flex justify-content-end">
        <a href="/clear-cache" target="_blank" class="btn btn-primary btn-sm">强制清除缓存</a>
    </div>
    <hr/>
    <div class="row">
        <div class="col-md-6">
            <img th:src="${productInfo.pic}" class="product-image"/>
        </div>
        <div class="col-md-6 product-info">
            <h2 class="product-title" th:text="${productInfo.title}"></h2>
            <p class="price">
                ¥<span id="salePrice">加载中...</span>
                <span class="original-price"
                >¥<span id="originalPrice">加载中...</span></span
                >
            </p>
            <div id="saleTimeInfo" class="sale-time">加载中...</div>
            <div id="stockInfo" class="stock-info card mb-3">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div class="stock-item">
                        <i class="bi bi-box-seam text-primary mr-2"></i>
                        <span class="text-muted">剩余库存：</span>
                        <strong>
                            <span id="remainingStock" class="text-success">--</span>
                            <span class="text-muted">/</span>
                            <span id="totalStock">--</span>
                        </strong>
                    </div>
                    <div class="stock-item">
                        <i class="bi bi-person-badge text-primary mr-2"></i>
                        <span class="text-muted">每人限购：</span>
                        <strong id="maxPurchasePerUser" class="text-primary">--</strong>
                    </div>
                </div>
            </div>
            <div id="countdownArea">
                <button class="btn btn-countdown" id="countdownButton" disabled>
                    <span class="countdown-label">加载中...</span>
                    <span id="countdownTimer"></span>
                </button>
            </div>
            <div
                    id="statusMessage"
                    class="status-message"
                    style="display: none"
            ></div>
            <div
                    id="saleHint"
                    class="alert alert-light border text-muted mt-3"
                    role="alert"
                    style="display: none"
            >
                <small>提示：秒杀商品数量有限，先到先得！</small>
            </div>
        </div>
    </div>
    <div class="row product-description">
        <div class="col-md-12">
            <h3>商品介绍</h3>
            <div th:utext="${productInfo.description}"></div>
        </div>
    </div>
</div>

<div class="modal fade" id="failModal" tabindex="-1" role="dialog" aria-labelledby="failModalLabel" aria-hidden="true"
     data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="failModalLabel">提示</h5>
            </div>
            <div class="modal-body" id="errorMessage">
                抢购失败，请稍后重试。
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script src="https://g.alicdn.com/code/lib/jquery/3.7.1/jquery.min.js"></script>
<script src="https://g.alicdn.com/code/lib/bootstrap/4.5.3/js/bootstrap.min.js"></script>
<script>
    $(document).ready(function () {
        const $countdownButton = $("#countdownButton");
        const $countdownTimer = $("#countdownTimer");
        const $saleTimeInfo = $("#saleTimeInfo");
        const $statusMessage = $("#statusMessage");
        const $countdownArea = $("#countdownArea");
        const $saleHint = $("#saleHint");

        let timeDiff = 0;

        function getParamFromUrl(paramName) {
            return new URLSearchParams(window.location.search).get(paramName) || '';
        }

        function formatTime(seconds) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            return [hours, minutes, secs]
                .map((v) => (v < 10 ? "0" + v : v))
                .join(":");
        }

        function parseDateTime(dateTimeString) {
            const [datePart, timePart] = dateTimeString.split(" ");
            const [year, month, day] = datePart.split("-");
            const [hour, minute, second] = timePart.split(":");
            return new Date(year, month - 1, day, hour, minute, second);
        }

        function formatDate(dateTimeString) {
            return dateTimeString;
        }

        function updateUI(data) {
            $("#salePrice").text((data.salePrice / 100).toFixed(2));
            $("#originalPrice").text((data.originalPrice / 100).toFixed(2));

            // 更新库存信息
            $("#totalStock").text(data.totalQuantity);
            $("#remainingStock").text(data.remainQuantity);
            $("#maxPurchasePerUser").text(data.maxPurchasePerUser);

            $statusMessage.hide();
            $countdownArea.show();
            $saleTimeInfo.hide();
            $saleHint.hide();

            if (data.status === "offline") {
                $statusMessage.text("商品已下架").addClass("status-offline").show();
                $countdownArea.hide();
            } else if (data.status === "online") {
                const now = parseDateTime(data.serverTime);
                const startTime = parseDateTime(data.startTime);
                const endTime = parseDateTime(data.endTime);

                if (now < startTime) {
                    $saleTimeInfo
                        .text("秒杀开始时间：" + formatDate(data.startTime))
                        .show();
                    startCountdown(startTime - now, "距离秒杀开始还有");
                    $countdownButton.prop("disabled", true);
                } else if (now >= startTime && now < endTime) {
                    $saleTimeInfo
                        .text("秒杀结束时间：" + formatDate(data.endTime))
                        .show();
                    if (data.remainQuantity > 0) {
                        startCountdown(endTime - now, "秒杀剩余时间");
                        $countdownButton.prop("disabled", false).text("立即抢购");
                        $saleHint.show();

                        if (data.userPurchased >= data.maxPurchasePerUser) {
                            $countdownButton.prop("disabled", true).text("已达购买上限");
                        }
                    } else {
                        $countdownButton.prop("disabled", true).text("已售罄");
                        $countdownTimer.text("");
                    }
                } else {
                    $saleTimeInfo.text("秒杀已结束").show();
                    $countdownButton.prop("disabled", true).text("秒杀已结束");
                    $countdownTimer.text("");
                }
            }
        }

        function startCountdown(duration, label) {
            let timeRemaining = Math.floor(duration / 1000);
            $countdownButton.find(".countdown-label").text(label);

            const countdownInterval = setInterval(function () {
                if (timeRemaining > 0) {
                    timeRemaining--;
                    $countdownTimer.text(formatTime(timeRemaining));
                } else {
                    clearInterval(countdownInterval);
                    fetchData();
                }
            }, 1000);
        }

        function fetchData() {
            const requestStartTime = new Date().getTime();
            const userId = getParamFromUrl('userId');
            $.ajax({
                url: `/product-info?userId=${userId}&productId=[[${productInfo.productId}]]`,
                method: "GET",
                success: function (response) {
                    if (response.success !== true) {
                        $('#errorMessage').text(response.message || '系统错误，请稍候重试！');
                        $('#failModal').modal('show');
                        return;
                    }
                    const data = response.data;
                    const responseTime = new Date().getTime();
                    const roundTripTime = responseTime - requestStartTime;
                    timeDiff =
                        data.serverTime -
                        responseTime +
                        Math.floor(roundTripTime / 2);
                    const dto = {
                        salePrice: data.flashSalePrice,
                        originalPrice: data.originalPrice,
                        startTime: data.startTime,
                        endTime: data.endTime,
                        serverTime: data.serverTime,
                        status: data.status,
                        totalQuantity: data.totalQuantity,
                        remainQuantity: data.remainQuantity,
                        maxPurchasePerUser: data.maxPurchasePerUser,
                        userPurchased: data.userPurchased
                    };
                    updateUI(dto);
                },
                error: function (xhr, status, error) {
                    console.error("Error fetching item info:", error);
                    $('#errorMessage').text('请求失败，请稍候重试！' + error);
                    $('#failModal').modal('show');
                },
            });
        }

        $countdownButton.on("click", function () {
            $button = $(this);
            $button.addClass("loading").prop('disabled', true).text('请求处理中...');
            const userId = getParamFromUrl('userId');
            $.ajax({
                url: `/create-order?userId=${userId}&productId=[[${productInfo.flashSaleProductId}]]`,
                method: "POST",
                success: function (response) {
                    if (response.success !== true) {
                        $('#errorMessage').text(response.message || '系统错误，请稍候重试！');
                        $('#failModal').modal('show');
                        $button.removeClass("loading").prop('disabled', false).text('立即抢购');
                        return;
                    }
                    document.location.href = '/order_detail.htm?orderId=' + response.data;
                },
                error: function (xhr, status, error) {
                    console.error("Error fetching item info:", xhr, status, error);
                    $('#errorMessage').text('请求失败，请稍候重试！' + error);
                    $('#failModal').modal('show');
                    $button.removeClass("loading").prop('disabled', false).text('立即抢购');
                },
            });
        });

        fetchData();
    });
</script>
</body>
</html>